package test;

import java.util.List;

import org.operamasks.faces.annotation.Action;
import org.operamasks.faces.annotation.BeforeRender;
import org.operamasks.faces.annotation.Bind;
import org.operamasks.faces.annotation.Inject;
import org.operamasks.faces.annotation.ManagedBean;
import org.operamasks.faces.annotation.ManagedBeanScope;
import org.operamasks.faces.annotation.ManagedProperty;
import org.operamasks.faces.annotation.SaveState;
import org.operamasks.faces.component.grid.impl.UIEditDataGrid;
import org.operamasks.faces.user.ajax.PartialUpdateManager;

@ManagedBean(name = "indexBean", scope = ManagedBeanScope.REQUEST)
public class IndexBean {

	@ManagedProperty("#{companyService}")
	private CompanyService companyService;

	@Bind
	private UIEditDataGrid companyGrid;

	@Bind(id = "companyGrid", attribute = "bindBean")
	private Class bindBean = Company.class;

	@Inject
	private PartialUpdateManager update;

	@SaveState
	private List<Company> companys;

	@Bind(id = "companyGrid")
	private List<Company> getCompanys() {
		return companys;
	}

	@Action
	public void moveup() {
		mergeData();
		Object[] selectedValues = companyGrid.getSelectedValues();
		if (selectedValues != null && selectedValues.length > 0) {
			int index = this.getModelDataIndex(companys,
					(Company) selectedValues[0]);
			if (index % companyGrid.getRows() != 0) {
				companys.add(index - 1, companys.get(index));
				companys.remove(index + 1);
				companyGrid.reload();
				companyGrid.setSelections(new int[] { index - 1 });
			}
		}
	}

	@Action
	public void movedown() {
		mergeData();
		Object[] selectedValues = companyGrid.getSelectedValues();
		if (selectedValues != null && selectedValues.length > 0) {
			int index = this.getModelDataIndex(companys,
					(Company) selectedValues[0]);
			if ((index + 1) % companyGrid.getRows() != 0) {
				if ((index + 2) > companys.size()) {
					return;
				}
				companys.add(index + 2, companys.get(index));
				companys.remove(index);
				companyGrid.reload();
				companyGrid.setSelections(new int[] { index + 1 });
			}
		}
	}

	private void mergeData() {
		Object[] modifiedData = (Object[]) companyGrid.getModifiedData();
		if (modifiedData != null) {
			for (Object data : modifiedData) {
				if (data instanceof Company) {
					Company modifiedDpm = (Company) data;
					int index = this.getModelDataIndex(companys, modifiedDpm);
					companys.set(index, modifiedDpm);
				}
			}
		}
	}

	private int getModelDataIndex(List<Company> modelData, Company record) {
		String id = record.getId();
		int index = 0;
		for (Company company : modelData) {
			if (id.equals(company.getId())) {
				return index;
			}
			index++;
		}
		return index;
	}

	@BeforeRender
	public void beforeRender(boolean isPostback) {
		if (!isPostback) {
			companys = companyService.findAll();
		}
	}
}
